package com.unieagle.exam.ui;

import java.io.File;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;
import com.unieagle.exam.R;
import com.unieagle.exam.account.AccountManager;
import com.unieagle.exam.camera.CameraActivity;
import com.unieagle.exam.http.BusinessConfig;
import com.unieagle.exam.http.IVolleyListener;
import com.unieagle.exam.http.TaskHelper;
import com.unieagle.exam.http.VolleyRequest;
import com.unieagle.exam.http.VolleyTask;
import com.unieagle.exam.model.UserInfoResult;
import com.unieagle.exam.ui.dialogs.ShareGridDialog;
import com.unieagle.exam.ui.dialogs.SlideUpMenuDialog;
import com.unieagle.exam.utils.HttpUtils;
import com.unieagle.exam.utils.SharedPreferenceUtils;
import com.unieagle.exam.utils.UriUtils;

public class SettingFragment extends Fragment implements IVolleyListener{
    private static final String TAG = "SettingFragment";

    private static final String[] HeaderMenu = new String[]{"选择更换头像的方式","拍照","从手机相册选择"};
    private static final int CHOSE_IMAGE = 7001;
    private static final int ACTIVATE = 7002;
    private static final int IDENTITY_UPLOAD = 7003;
    private int op = -1;

    private ImageButton mIbBack;

    private ImageView mIvHeader;
    private ViewGroup mVgName;
    private TextView mTvNameValue;
    private ViewGroup mVgIdentity;
    private TextView mTvIdentityValue;
    private ViewGroup mVgMineBank;
    private ViewGroup mVgSurplusTimes;
    private TextView mTvSurplusTimsValue;
    private ViewGroup mVgActivate;
    private ViewGroup mVgSettingShare;
    private ViewGroup mVgAboutUs;
    private ViewGroup mVgAppUpload;
    private Button mBtLogout;

    private SlideUpMenuDialog mHeaderMenuDialog;
    private ShareGridDialog mShareDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.setting_fragment_layout,container,false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        find(view);
        listen();
        value();
    }

    private void find(View view){
        mIbBack = (ImageButton) view.findViewById(R.id.back);
        mIvHeader = (ImageView) view.findViewById(R.id.setting_header);
        mVgName = (ViewGroup) view.findViewById(R.id.item_name);
        mTvNameValue = (TextView) view.findViewById(R.id.item_name_value);
        mVgIdentity = (ViewGroup) view.findViewById(R.id.item_identity_upload);
        mTvIdentityValue = (TextView) view.findViewById(R.id.item_identity_upload_value);
        mVgMineBank = (ViewGroup) view.findViewById(R.id.item_mine_bank);
        mVgSurplusTimes = (ViewGroup) view.findViewById(R.id.item_surplus_times);
        mTvSurplusTimsValue = (TextView)view.findViewById(R.id.item_surplus_times_value) ;
        mVgAboutUs = (ViewGroup) view.findViewById(R.id.item_about_us);
        mVgSettingShare = (ViewGroup) view.findViewById(R.id.item_setting_share);
        mVgActivate = (ViewGroup) view.findViewById(R.id.item_activate);
        mVgAppUpload = (ViewGroup)view.findViewById(R.id.item_app_update);
        mBtLogout = (Button)view.findViewById(R.id.logout);
    }

    private void listen(){
        mIvHeader.setOnClickListener(mOnClickListner);
        mVgIdentity.setOnClickListener(mOnClickListner);
        mVgMineBank.setOnClickListener(mOnClickListner);
        mVgSurplusTimes.setOnClickListener(mOnClickListner);
        mVgAboutUs.setOnClickListener(mOnClickListner);
        mVgAppUpload.setOnClickListener(mOnClickListner);
        mBtLogout.setOnClickListener(mOnClickListner);
        mIbBack.setOnClickListener(mOnClickListner);
        mVgSettingShare.setOnClickListener(mOnClickListner);
        mVgActivate.setOnClickListener(mOnClickListner);
    }

    private void value(){
        mTvNameValue.setText(AccountManager.getInstance().getUserName());
        if(AccountManager.getInstance().getUserInfo().getActivation_status().equals("activation_active")) {
        	mVgActivate.setVisibility(View.GONE);
        	mTvSurplusTimsValue.setText(R.string.no_limit);
        } else {
        	mVgActivate.setVisibility(View.VISIBLE);
        	mTvSurplusTimsValue.setText(AccountManager.getInstance().getTrailCount());
        }
        String headerUri = HttpUtils.getHost() + AccountManager.getInstance().getCertificateAvatarUrl();
        if(!TextUtils.isEmpty(headerUri)) {
            displayHeader(headerUri);
        }
        if(!TextUtils.isEmpty(AccountManager.getInstance().getCertificateBackUrl())) {
        	mTvIdentityValue.setText(R.string.already_upload);
        } else {
        	mTvIdentityValue.setText(R.string.not_upload);
        }
    }

    private View.OnClickListener mOnClickListner = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int id = view.getId();
            Intent i;
            switch (id){
                case R.id.back:
                    getActivity().finish();
                    break;
                case R.id.setting_header:
                    headerMenu();
                    break;
                case R.id.item_identity_upload:
                    startActivityForResult(new Intent(getActivity(), IdentityUploadActivity.class), IDENTITY_UPLOAD);
                    break;
                case R.id.item_mine_bank:
                	if(AccountManager.getInstance().getUserInfo().getActivation_status().equals("activation_active")) {
	                	i = new Intent(getActivity(), AddSubjectActivity.class);
						startActivity(i);
                	} else {
                		Toast.makeText(getActivity(), "请先激活账户", Toast.LENGTH_SHORT).show();
                	}
                    break;
                case R.id.item_surplus_times:
                    break;
                case R.id.item_about_us:
                    startActivity(new Intent(getActivity(), AboutUsActivity.class));
                    break;
                case R.id.item_app_update:
                    startActivity(new Intent(getActivity(), UpdateActivity.class));
                    break;
                case R.id.item_setting_share:
                    shareDialog();
                    break;
                case R.id.item_activate:
                	activate();
                	break;
                case R.id.logout:
                	AccountManager.getInstance().logout();
                	SharedPreferenceUtils.setPushToken(getActivity(), "");
                	i = new Intent(getActivity(), LoginActivity.class);
                	i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                	startActivity(i);
                	break;
            }
        }
    };
    
    private void activate() {
    	VolleyTask activateTask = TaskHelper.createRequestActivationTask();
    	op = ACTIVATE;
    	activateTask.setVolleyListener(this);
        VolleyRequest.getInstance().request(activateTask);
        ((BaseActivity)getActivity()).showProgress("正在激活");
    }

    private void headerMenu(){
        if(mHeaderMenuDialog == null) {
            mHeaderMenuDialog = new SlideUpMenuDialog(getActivity());
            mHeaderMenuDialog.setOnItemClickListener(new ListView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    choseImage(i);
                }
            });
            if (Build.VERSION.SDK_INT >= 21) {
                mHeaderMenuDialog.create();
            }
        }
        mHeaderMenuDialog.show(1, HeaderMenu);
    }

    private void shareDialog(){
        if(mShareDialog == null){
            mShareDialog = new ShareGridDialog(getActivity());
            if (Build.VERSION.SDK_INT >= 21) {
                mShareDialog.create();
            }
        }
        mShareDialog.setActivity(getActivity());
        mShareDialog.show();
    }

    public void choseImage(int type){
        switch (type){
            case 1:
                startActivityForResult(new Intent(getActivity(), CameraActivity.class),CHOSE_IMAGE);
                break;
            case 2:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "选择图片"), CHOSE_IMAGE);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == CHOSE_IMAGE){
            Log.d(TAG, "GET IMAGE ");
            if(data != null) {
                String path = UriUtils.getPath(getActivity(), data.getData());
                File file = new File(path);
                if(file.exists()) {
                    VolleyTask task = TaskHelper.createUploadImageTask(BusinessConfig.UPLOAD_IMAGE_TYPE_AVATAR, file);
                    task.setVolleyListener(this);
                    op = CHOSE_IMAGE;
                    VolleyRequest.getInstance().request(task);
                    ((BaseActivity)getActivity()).showProgress("上传中");
                }
            }
        } else if(requestCode == IDENTITY_UPLOAD && resultCode == Activity.RESULT_OK) {
        	mTvIdentityValue.setText(R.string.already_upload);
        }
    }
    private DisplayImageOptions mHeaderOption;
    private void displayHeader(String uri){
        if(mHeaderOption == null) {
            mHeaderOption = new DisplayImageOptions.Builder()
                    .cacheInMemory(true)//设置下载的图片是否缓存在内存中
                    .cacheOnDisk(true)
                    .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//
                    .displayer(new RoundedBitmapDisplayer(360))//是否设置为圆角，弧度为多少
                    .build();//构建完成

        }
        ImageLoader.getInstance().displayImage(uri, mIvHeader,mHeaderOption);
    }

    @Override
    public void onComplete(VolleyTask task, Object result) {
    	((BaseActivity)getActivity()).dismissProgress();
        if(result instanceof UserInfoResult){
            AccountManager.getInstance().updateUserInfoResult((UserInfoResult)result);
            if(op == CHOSE_IMAGE) { //上传头像
            	String headerUri = HttpUtils.getHost() + AccountManager.getInstance().getCertificateAvatarUrl();
            	if(!TextUtils.isEmpty(headerUri)) {
            		DiskCacheUtils.removeFromCache(headerUri, ImageLoader.getInstance().getDiskCache());    
                    MemoryCacheUtils.removeFromCache(headerUri, ImageLoader.getInstance().getMemoryCache());
                    displayHeader(headerUri);
                }
                Toast.makeText(getActivity(),"上传成功", Toast.LENGTH_SHORT).show();
            } else { //申请激活
            	Toast.makeText(getActivity(),"激活成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onError(VolleyTask task, VolleyError volleyError) {
    	((BaseActivity)getActivity()).dismissProgress();
    	if(op == CHOSE_IMAGE) {
    		Toast.makeText(getActivity(),"上传失败", Toast.LENGTH_SHORT).show();
    	} else {
    		Toast.makeText(getActivity(),"激活失败", Toast.LENGTH_SHORT).show();
    	}
    }
    
}
